import fs from 'fs';
import path from 'path';

type ErrorRecord = {
  timestamp: Date;
  error: Error;
  context: any;
  solution?: string;
};

class IntelligentCompatibilityEngine {
  private errorLogPath: string;
  private repairRules: Map<string, (error: Error) => string>;

  constructor(logDir = './logs') {
    this.errorLogPath = path.join(logDir, 'compatibility-errors.log');
    this.ensureLogDirectory(logDir);
    this.repairRules = new Map();
    this.initBasicRules();
  }

  private ensureLogDirectory(dir: string) {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
  }

  private initBasicRules() {
    // 类型错误修复规则
    this.repairRules.set('TS2322', (error) => {
      const match = error.message.match(/Type '(.*)' is not assignable to type '(.*)'/);
      return match ? `// @ts-ignore\n// 智能修复类型不匹配: ${match[1]} → ${match[2]}` : '';
    });

    // 未定义属性修复规则
    this.repairRules.set('TS2339', (error) => {
      const match = error.message.match(/Property '(.*)' does not exist on type '(.*)'/);
      return match ? `// @ts-expect-error\n// 智能添加缺失属性: ${match[1]}` : '';
    });
  }

  async handleError(error: Error, context: any = {}): Promise<string> {
    const errorRecord: ErrorRecord = {
      timestamp: new Date(),
      error,
      context
    };

    // 尝试自动修复
    const solution = this.attemptRepair(error);
    if (solution) {
      errorRecord.solution = solution;
    }

    // 记录错误
    await this.logError(errorRecord);

    return solution || '需要人工干预';
  }

  private attemptRepair(error: Error): string | undefined {
    for (const [pattern, handler] of this.repairRules) {
      if (error.message.includes(pattern)) {
        return handler(error);
      }
    }
    return undefined;
  }

  private async logError(record: ErrorRecord) {
    const logEntry = JSON.stringify(record, null, 2);
    await fs.promises.appendFile(this.errorLogPath, `${logEntry},\n`, 'utf8');
  }

  addRepairRule(pattern: string, handler: (error: Error) => string) {
    this.repairRules.set(pattern, handler);
  }
}

export const compatibilityEngine = new IntelligentCompatibilityEngine();